package com.bgs.engineering.security.customizelogin.phone;

import com.bgs.engineering.api.sysUser.entiy.SysUser;
import com.bgs.engineering.api.sysUser.service.SysUserService;
import com.bgs.engineering.util.RedisUtil;
import com.bgs.engineering.util.constants.CommonConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName EmailAuthenticationProvider
 * @Description 认证信息
 * @Author zcy
 * @Date 2023/4/5 15:20
 **/
@Component
public class PhoneCodeAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    SysUserService sysUserService;

    /**
     *  * 认证处理，返回一个Authentication的实现类则代表认证成功，返回null则代表认证失败
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (!supports(authentication.getClass())) {
            return null;
        }
        SysUser user = (SysUser)authentication.getPrincipal();
        String phoneCode = (String)authentication.getCredentials();
        // 清理redis缓存
        String key = CommonConstants.CACHE_PHONE_CODE+phoneCode;
        RedisUtil.del(key);
        //获取用户权限信息
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//        if (sysUser != null) {
//            //获取该用户所拥有的权限
//            List<SysPermission> sysPermissions = sysPermissionService.selectListByUser(sysUser.getId());
//            // 声明用户授权
//            sysPermissions.forEach(sysPermission -> {
//                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysPermission.getPermissionCode());
//                grantedAuthorities.add(grantedAuthority);
//            });
//        }
        PhoneCodeAuthenticationToken result  = new PhoneCodeAuthenticationToken(user,grantedAuthorities);
        result.setDetails(authentication.getDetails());
        return result;
    }



    /**
     * 如果该AuthenticationProvider支持传入的Authentication对象，则返回true
     */
    @Override
    public boolean supports(Class<?> aClass) {
        return PhoneCodeAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
